#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Windows 系统监控工具 - 命令行演示版本
"""

import time
import os
import sys
from system_monitor import SystemMonitor

def clear_screen():
    """清屏"""
    os.system('cls' if os.name == 'nt' else 'clear')

def format_bytes(bytes_value):
    """格式化字节数"""
    for unit in ['B', 'KB', 'MB', 'GB', 'TB']:
        if bytes_value < 1024.0:
            return f"{bytes_value:.2f} {unit}"
        bytes_value /= 1024.0
    return f"{bytes_value:.2f} PB"

def display_system_info(monitor):
    """显示系统信息"""
    print("=" * 60)
    print("           Windows 系统监控工具 - 实时数据")
    print("=" * 60)
    
    # CPU 信息
    cpu_info = monitor.get_cpu_info()
    print(f"\n🖥️  CPU 信息:")
    print(f"   使用率: {cpu_info['usage_percent']:.1f}%")
    print(f"   核心数: {cpu_info['core_count']} 个")
    print(f"   频率: {cpu_info['current_freq']:.0f} MHz")
    
    # 内存信息
    memory_info = monitor.get_memory_info()
    print(f"\n💾 内存信息:")
    print(f"   总内存: {memory_info['total']:.2f} GB")
    print(f"   已使用: {memory_info['used']:.2f} GB ({memory_info['usage_percent']:.1f}%)")
    print(f"   可用: {memory_info['available']:.2f} GB")
    
    # 磁盘信息
    disk_info = monitor.get_disk_info()
    print(f"\n💿 磁盘信息 (C盘):")
    print(f"   总容量: {disk_info['total']:.2f} GB")
    print(f"   已使用: {disk_info['used']:.2f} GB ({disk_info['usage_percent']:.1f}%)")
    print(f"   可用: {disk_info['free']:.2f} GB")
    
    # 网络信息
    network_info = monitor.get_network_info()
    print(f"\n🌐 网络信息:")
    print(f"   发送: {format_bytes(network_info['bytes_sent'])}")
    print(f"   接收: {format_bytes(network_info['bytes_recv'])}")
    
    # 进程信息（显示前5个占用CPU最高的进程）
    processes = monitor.get_process_list()
    top_processes = processes[:5]  # 已经按CPU使用率排序了
    
    print(f"\n🔄 CPU占用最高的进程 (前5个):")
    print(f"{'PID':<8} {'名称':<20} {'CPU%':<8} {'内存(MB)':<12}")
    print("-" * 50)
    for proc in top_processes:
        print(f"{proc['pid']:<8} {proc['name'][:18]:<20} {proc['cpu_percent']:<8.1f} {proc['memory_mb']:<12.1f}")

def main():
    """主函数"""
    try:
        monitor = SystemMonitor()
        print("正在启动系统监控工具...")
        print("按 Ctrl+C 退出")
        time.sleep(2)
        
        while True:
            clear_screen()
            display_system_info(monitor)
            print(f"\n⏰ 更新时间: {time.strftime('%Y-%m-%d %H:%M:%S')}")
            print("\n按 Ctrl+C 退出程序...")
            
            # 等待3秒后刷新
            time.sleep(3)
            
    except KeyboardInterrupt:
        print("\n\n程序已退出，感谢使用！")
        sys.exit(0)
    except Exception as e:
        print(f"程序运行出错: {e}")
        input("按任意键退出...")
        sys.exit(1)

if __name__ == "__main__":
    main()